package service

import (
	"context"
	"strings"
	"time"

	"awesomeProject/internal/model"
	"awesomeProject/internal/repository"
	"awesomeProject/pkg/errors"
)

type PostService interface {
	// 帖子管理
	CreatePost(ctx context.Context, userID uint, req *CreatePostRequest) (*model.Post, error)
	GetPost(ctx context.Context, postID uint) (*model.Post, error)
	UpdatePost(ctx context.Context, userID, postID uint, req *UpdatePostRequest) error
	DeletePost(ctx context.Context, userID, postID uint) error

	// 帖子查询
	GetPostList(ctx context.Context, req *PostListRequest) ([]*model.Post, int64, error)
	GetPostsByCategory(ctx context.Context, categoryID uint, page, pageSize int) ([]*model.Post, int64, error)
	GetPostsByUser(ctx context.Context, userID uint, page, pageSize int) ([]*model.Post, int64, error)
	GetUserFavorites(ctx context.Context, userID uint, page, pageSize int) ([]*model.Post, int64, error)

	// 点赞收藏
	LikePost(ctx context.Context, userID, postID uint) error
	UnlikePost(ctx context.Context, userID, postID uint) error
	FavoritePost(ctx context.Context, userID, postID uint) error
	UnfavoritePost(ctx context.Context, userID, postID uint) error
	GetPostStats(ctx context.Context, postID uint) (*PostStats, error)
}

type postService struct {
	postRepo     repository.PostRepository
	userRepo     repository.UserRepository
	categoryRepo repository.CategoryRepository
	aiService    AIService
}

// NewPostService 创建帖子服务实例
func NewPostService(
	postRepo repository.PostRepository,
	userRepo repository.UserRepository,
	categoryRepo repository.CategoryRepository,
	aiService AIService,
) PostService {
	return &postService{
		postRepo:     postRepo,
		userRepo:     userRepo,
		categoryRepo: categoryRepo,
		aiService:    aiService,
	}
}

// 请求结构体定义
type CreatePostRequest struct {
	Title         string `json:"title" binding:"required,min=1,max=100"`
	Content       string `json:"content" binding:"required,min=10"`
	CategoryID    uint   `json:"category_id" binding:"omitempty"`
	Tags          string `json:"tags" binding:"omitempty,max=200"`
	AutoClassify  bool   `json:"auto_classify" binding:"omitempty"`
	AutoSummary   bool   `json:"auto_summary" binding:"omitempty"`
}

type UpdatePostRequest struct {
	Title      string `json:"title" binding:"omitempty,min=1,max=100"`
	Content    string `json:"content" binding:"omitempty,min=10"`
	CategoryID uint   `json:"category_id" binding:"omitempty"`
	Tags       string `json:"tags" binding:"omitempty,max=200"`
}

type PostListRequest struct {
	Page     int    `json:"page" binding:"omitempty,min=1"`
	PageSize int    `json:"page_size" binding:"omitempty,min=1,max=100"`
	Keyword  string `json:"keyword" binding:"omitempty,max=50"`
	SortBy   string `json:"sort_by" binding:"omitempty,oneof=created_at updated_at likes"`
	Order    string `json:"order" binding:"omitempty,oneof=asc desc"`
}

type PostStats struct {
	LikeCount     int64 `json:"like_count"`
	FavoriteCount int64 `json:"favorite_count"`
	CommentCount  int64 `json:"comment_count"`
}

// CreatePost 创建帖子
func (s *postService) CreatePost(ctx context.Context, userID uint, req *CreatePostRequest) (*model.Post, error) {
	// 验证用户是否存在
	_, err := s.userRepo.GetByID(ctx, userID)
	if err != nil {
		return nil, err
	}

	// 处理AI智能分类
	var categoryID uint = req.CategoryID
	if req.AutoClassify && req.CategoryID == 0 {
		// 获取现有分类列表
		existingCategories, err := s.categoryRepo.GetAll(ctx)
		if err != nil {
			return nil, errors.New(errors.InternalError, "获取分类列表失败", err.Error())
		}
		
		// 构建分类名称列表
		categoryNames := make([]string, len(existingCategories))
		for i, cat := range existingCategories {
			categoryNames[i] = cat.Name
		}
		
		// 使用AI智能分类
		categoryName, description, isNew, err := s.aiService.SmartClassify(ctx, req.Title, req.Content, categoryNames)
		if err != nil {
			return nil, errors.New(errors.AIServiceError, "AI分类失败", err.Error())
		}
		
		if isNew {
			// 创建新分类
			newCategory := &model.Category{
				Name:        categoryName,
				Description: description,
			}
			if err := s.categoryRepo.Create(ctx, newCategory); err != nil {
				return nil, errors.New(errors.InternalError, "创建新分类失败", err.Error())
			}
			categoryID = newCategory.ID
		} else {
			// 使用现有分类
			category, err := s.categoryRepo.GetByName(ctx, categoryName)
			if err != nil {
				return nil, errors.New(errors.InternalError, "获取分类失败", err.Error())
			}
			categoryID = category.ID
		}
	} else if req.CategoryID != 0 {
		// 验证分类是否存在
		_, err = s.categoryRepo.GetByID(ctx, req.CategoryID)
		if err != nil {
			return nil, err
		}
	} else {
		return nil, errors.New(errors.InvalidParams, "请指定文章分类或启用自动分类")
	}

	// 处理AI自动摘要
	var summary string
	if req.AutoSummary {
		summary, err = s.aiService.GenerateSummary(ctx, req.Content)
		if err != nil {
			// 摘要生成失败不影响文章创建，只记录错误
			summary = ""
		}
	}

	// 创建帖子模型
	post := &model.Post{
		Title:      strings.TrimSpace(req.Title),
		Content:    strings.TrimSpace(req.Content),
		Summary:    summary,
		CategoryID: categoryID,
		UserID:     userID,
		Tags:       strings.TrimSpace(req.Tags),
		Status:     1, // 默认发布状态
		CreatedAt:  time.Now(),
		UpdatedAt:  time.Now(),
	}
	// 调用仓储层repository创建帖子
	if err = s.postRepo.Create(ctx, post); err != nil {
		return nil, err
	}
	return post, nil
}

// GetPost 获取帖子详情
func (s *postService) GetPost(ctx context.Context, postID uint) (*model.Post, error) {
	// 调用仓储层repository查询帖子
	post, err := s.postRepo.GetByID(ctx, postID)
	if err != nil {
		return nil, err
	}
	return post, err
}

// UpdatePost 更新帖子
func (s *postService) UpdatePost(ctx context.Context, userID, postID uint, req *UpdatePostRequest) error {
	// 先获取帖子的信息
	post, err := s.postRepo.GetByID(ctx, postID)
	if err != nil {
		return err
	}
	// 验证权限，只让作者过更新
	if post.UserID != userID {
		return errors.ErrPostNotOwner
	}
	// 想要修改分类的话 需要确定分类存不存在
	if req.CategoryID != 0 && req.CategoryID != post.CategoryID {
		_, err = s.categoryRepo.GetByID(ctx, req.CategoryID)
		if err != nil {
			return err
		}
		post.CategoryID = req.CategoryID
	}
	// 更新字段
	if req.Title != "" {
		post.Title = strings.TrimSpace(req.Title)
	}
	if req.Content != "" {
		post.Content = strings.TrimSpace(req.Content)
	}
	if req.Tags != "" {
		post.Tags = strings.TrimSpace(req.Tags)
	}
	// 更新更新时间
	post.UpdatedAt = time.Now()
	return s.postRepo.Update(ctx, post)
}

// DeletePost 删除帖子
func (s *postService) DeletePost(ctx context.Context, userID, postID uint) error {
	// 先获取帖子信息
	post, err := s.postRepo.GetByID(ctx, postID)
	if err != nil {
		return err
	}
	// 验证权限，只有帖子作者可以删除
	if post.UserID != userID {
		return errors.ErrPostNotOwner
	}
	return s.postRepo.Delete(ctx, postID)
}

// GetPostList 获取帖子列表
func (s *postService) GetPostList(ctx context.Context, req *PostListRequest) ([]*model.Post, int64, error) {
	// 设置默认值
	if req.Page <= 0 {
		req.Page = 1
	}
	if req.PageSize <= 0 || req.PageSize > 100 {
		req.PageSize = 10
	}
	return s.postRepo.List(ctx, req.Page, req.PageSize)
}

// GetPostsByCategory 获取分类下的帖子列表
func (s *postService) GetPostsByCategory(ctx context.Context, categoryID uint, page, pageSize int) ([]*model.Post, int64, error) {
	// 验证分类是否存在
	_, err := s.categoryRepo.GetByID(ctx, categoryID)
	if err != nil {
		return nil, 0, err
	}
	// 参数验证
	if page <= 0 {
		page = 1
	}
	if pageSize <= 0 || pageSize >= 100 {
		pageSize = 10
	}
	return s.postRepo.ListByCategory(ctx, categoryID, page, pageSize)
}

// GetPostsByUser 获取用户发布的帖子列表
func (s *postService) GetPostsByUser(ctx context.Context, userID uint, page, pageSize int) ([]*model.Post, int64, error) {
	// 验证用户是否存在
	_, err := s.userRepo.GetByID(ctx, userID)
	if err != nil {
		return nil, 0, err
	}
	// 参数验证
	if page <= 0 {
		page = 1
	}
	if pageSize <= 0 || pageSize >= 100 {
		pageSize = 10
	}
	return s.postRepo.ListByUser(ctx, userID, page, pageSize)
}

// LikePost 点赞帖子
func (s *postService) LikePost(ctx context.Context, userID, postID uint) error {
	return s.postRepo.AddLike(ctx, postID, userID)
}

// UnlikePost 取消点赞
func (s *postService) UnlikePost(ctx context.Context, userID, postID uint) error {
	return s.postRepo.RemoveLike(ctx, postID, userID)
}

// FavoritePost 收藏帖子
func (s *postService) FavoritePost(ctx context.Context, userID, postID uint) error {
	return s.postRepo.AddFavourite(ctx, postID, userID)
}

// UnfavoritePost 取消收藏
func (s *postService) UnfavoritePost(ctx context.Context, userID, postID uint) error {
	return s.postRepo.RemoveFavourite(ctx, postID, userID)
}

// GetPostStats 获取帖子统计信息
func (s *postService) GetPostStats(ctx context.Context, postID uint) (*PostStats, error) {
	// 验证帖子是否存在
	_, err := s.postRepo.GetByID(ctx, postID)
	if err != nil {
		return nil, err
	}

	// 获取点赞数
	likeCount, err := s.postRepo.GetLikeCount(ctx, postID)
	if err != nil {
		return nil, err
	}

	// 获取收藏数
	favoriteCount, err := s.postRepo.GetFavoriteCount(ctx, postID)
	if err != nil {
		return nil, err
	}

	return &PostStats{
		LikeCount:     likeCount,
		FavoriteCount: favoriteCount,
		CommentCount:  0, // 需要评论服务实现后补充
	}, nil
}

// GetUserFavorites 获取用户收藏的帖子列表
func (s *postService) GetUserFavorites(ctx context.Context, userID uint, page, pageSize int) ([]*model.Post, int64, error) {
	// 验证用户是否存在
	_, err := s.userRepo.GetByID(ctx, userID)
	if err != nil {
		return nil, 0, errors.ErrUserNotFound
	}

	// 设置默认分页参数
	if page <= 0 {
		page = 1
	}
	if pageSize <= 0 || pageSize > 100 {
		pageSize = 10
	}

	// 获取用户收藏的帖子列表
	return s.postRepo.ListUserFavorites(ctx, userID, page, pageSize)
}
